package com.develop.BeanUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class FormatConversion {
	/**
	 * Big-Endian,将int数值转换为占四个字节的byte数组，本方法适用于(高位在前，低位在后)的顺序。
	 */
	public static byte[] intToBytes2(int value) {
		byte[] src = new byte[4];
		src[0] = (byte) ((value >> 24) & 0xFF);
		src[1] = (byte) ((value >> 16) & 0xFF);
		src[2] = (byte) ((value >> 8) & 0xFF);
		src[3] = (byte) (value & 0xFF);
		return src;
	}

	public static byte[] toLH(int n) {
		byte[] b = new byte[4];
		b[0] = (byte) (n & 0xff);
		b[1] = (byte) (n >> 8 & 0xff);
		b[2] = (byte) (n >> 16 & 0xff);
		b[3] = (byte) (n >> 24 & 0xff);
		return b;
	}

	public static int bytesToInt2(byte[] src, int offset) {
		int value;
		value = (int) (((src[offset] & 0xFF) << 24) | ((src[offset + 1] & 0xFF) << 16) | ((src[offset + 2] & 0xFF) << 8) | (src[offset + 3] & 0xFF));
		return value;
	}

	/**
	 * Big-Endian,将short数值转换为占二个字节的byte数组，本方法适用于(高位在前，低位在后)的顺序。
	 */
	public static byte[] shortToBytes2(short value) {
		byte[] src = new byte[2];
		src[0] = (byte) ((value >> 8) & 0xFF);
		src[1] = (byte) (value & 0xFF);
		return src;
	}

	public static short bytesToShort2(byte[] src, int offset) {
		short value;
		value = (short) (((src[offset] & 0xFF) << 8) | (src[offset + 1] & 0xFF));
		return value;
	}

	/**
	 * 单字节处理为字节数组
	 */
	public static byte[] byteToBytes2(byte value) {
		byte[] src = new byte[1];
		src[0] = value;
		return src;
	}

	public static byte bytesToByte(byte[] src, int offset) {
		byte value;
		value = (src[offset]);
		return value;
	}

	public static byte[] objectToByteArray(Object obj) throws IOException {
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
		objectOutputStream.writeObject(obj);
		return byteArrayOutputStream.toByteArray();
	}
}
